package com.geek.novel.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
import com.geek.novel.R
import com.geek.novel.activity.base.TitleBarActivity
import com.geek.novel.bo.AppContext
import com.geek.novel.common.Constant
import com.geek.novel.entity.AppTypeface
import com.geek.novel.network.RslHandler
import com.geek.novel.services.AppTypefaceRepository
import com.geek.novel.services.NovelService
import com.geek.novel.utils.*
import com.geek.novel.vo.ApiErrorResult
import com.geek.novel.vo.ApiResult
import kotlinx.android.synthetic.main.activity_typeface.*
import java.io.File
import java.lang.Exception


/**
 * 字体文件选择页面
 */
class TypefaceActivity: TitleBarActivity(), RslHandler {

	override fun pageName(): String{
		return AppContext.getContext().getString(R.string.title_bar_page_typeface)
	}

	/**默认字体*/
	private val defaultTypeFace = "default_typeface"

	/**列表数据*/
	private val listData = arrayListOf<AppTypeface>()

	/**列表的适配器*/
	private lateinit var listViewAdapter: ListAdapter

	/**小说服务*/
	private lateinit var novelService: NovelService

	/**文件下载工具*/
	private lateinit var downloadUtil: DownloadUtil

	/**字体文件的数据库类*/
	private var appTypefaceRepository = AppTypefaceRepository()

	@SuppressLint("HandlerLeak")
	private val handler = object: Handler(){
		override fun handleMessage(msg: Message) {
			val key = msg.data?.get("key")
			val typeface = listData.find { it.typeCode == key }
			if(typeface != null){
				when(msg.what){
					/**下载中*/
					DownloadUtil.DOWNLOAD_PROGRESS->{
						typeface.progress = msg.arg1
					}
					/**下载完成*/
					DownloadUtil.DOWNLOAD_SUCCESS->{
						typeface.progress = null
					}
					/**取消下载、下载失败*/
					DownloadUtil.CANCEL_DOWNLOAD,
					DownloadUtil.DOWNLOAD_ERROR -> {// 取消更新
						val err = if(msg.obj == null)null else msg.obj as Throwable
						if(err != null){
							ToastUtils.toast(err.message)
						}
						typeface.progress = null
					}
				}

				updateListItem(typeface)
			}
		}
	}

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_typeface)

		//显示标题栏右侧按钮
		super.showTitleBtn("管理")

		novelService = NovelService(this)
		novelService.getTypefaceList()

		downloadUtil = DownloadUtil(handler)

		//初始化字体文件列表
		val list = appTypefaceRepository.findAll()
		this.initListData(list)

	}

	/**初始化字体文件列表*/
	private fun initListData(list: List<AppTypeface>){
		listData.clear()
		//默认字体
		val defaultTypeface = AppTypeface()
		defaultTypeface.typeName = "跟随系统"
		defaultTypeface.typeCode = defaultTypeFace
		listData.add(defaultTypeface)
		listData.addAll(list)
	}

	/**附加控件*/
	override fun attachViewChild() {
		listViewAdapter = ListAdapter(this, R.layout.listview_typeface, listData)
		lv_typeface_list.adapter = listViewAdapter
	}

	override fun clickEvent(id: Int, v: View) {
	}

	/**是否是管理模式*/
	private var isManagerMode = false
	/**标题右侧按钮的点击事件*/
	override fun onTitleBtnClick(view: View) {
		this.isManagerMode = !this.isManagerMode
		listViewAdapter.notifyDataSetChanged()

		super.updateTitleBtnText(if(this.isManagerMode) "取消" else "管理")
	}

	/**更新某一项*/
	fun updateListItem(typeface: AppTypeface){
		val itemIndex = listData.indexOf(typeface)
		//获取第一个可以看到的item位置
		val firstVisiblePosition: Int = lv_typeface_list.firstVisiblePosition
		//获取最后一个可以看到的item位置
		val lastVisiblePosition: Int = lv_typeface_list.lastVisiblePosition
		//判断是否在范围内
		if (itemIndex in firstVisiblePosition..lastVisiblePosition) {
			val view: View = lv_typeface_list.getChildAt(itemIndex - firstVisiblePosition)
			checkDownloadTypeface(view, typeface)
		}
	}

	/**加载*/

	/**列表项的适配器*/
	inner class ListAdapter(context: Context, private val resourceId: Int, private val list: List<AppTypeface>) : ArrayAdapter<AppTypeface>(context, resourceId, list) {
		@SuppressLint("ViewHolder", "SetTextI18n")
		override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
			val view = LayoutInflater.from(context).inflate(resourceId, null)
			val typeface = list[position]
			//字体名称
			setViewText(view, R.id.tv_typeface_name, typeface.typeName)

			checkDownloadTypeface(view, typeface)

			return view
		}
	}

	/**根据文件状态显示不同的按钮*/
	private fun checkDownloadTypeface(view: View, typeface: AppTypeface){
		//文件大小
		val size = FormatUtil.isNullToFloatZero(typeface.fileSize)/1024/1024
		val sizeStr = CommUtil.getDecimalFormat(size.toDouble()) + "M"
		if(typeface.typeCode != defaultTypeFace){
			setViewText(view, R.id.tv_typeface_size, sizeStr)
		}else{
			setViewText(view, R.id.tv_typeface_size, "")
		}

		//删除按钮
		val ivTypefaceDelete = view.findViewById<View>(R.id.iv_typeface_delete)
		ivTypefaceDelete.visibility = View.GONE
		ivTypefaceDelete.setOnClickListener{
			this.deleteTypefaceFile(typeface)
		}

		//获取当前使用的字体文件
		val curSelectTypeface = SPUtil[SPUtil.book_typeface, "", SPUtil.SP_SYSTEM_SETUP] as String

		val tvTypefaceDownload = view.findViewById<TextView>(R.id.tv_typeface_download)

		val file = if(!TextUtils.isEmpty(typeface.fileName)){
			File(Constant.TypefacePath, typeface.fileName)
		}else{
			null
		}

		val isFileExist = file != null && file.exists() && typeface.fileSize!!.toLong() == file.length()

		//判断本地文件是否存在并显示，存在则显示字体
		if(!typeface.error){
			try{
				val tvTypefaceName = view.findViewById<TextView>(R.id.tv_typeface_name)
				tvTypefaceName.typeface = Typeface.DEFAULT
				if(typeface.progress == null && isFileExist) {
					tvTypefaceName.typeface = Typeface.createFromFile(file)
//					LogCatUtil.d("???", "大小：${typeface.fileSize}, 文件大小：${file!!.length()}")
				}
			}catch (e: Exception){
				LogCatUtil.e("???", e.message)
				typeface.error = true
			}
		}

		//判断字体文件的状态并显示不同的按钮
		if(typeface.typeCode == defaultTypeFace){//默认字体
			val isDefault = TextUtils.isEmpty(curSelectTypeface)
			tvTypefaceDownload.text = if(isDefault){
				tvTypefaceDownload.background = this.getDrawable(R.drawable.selector_round_btn_disabled)
				"已使用"
			}else{
				tvTypefaceDownload.background = this.getDrawable(R.drawable.selector_round_btn_primary)
				"使用"
			}
			tvTypefaceDownload.setOnClickListener {
				if(isDefault){
					return@setOnClickListener
				}
				ToastUtils.toast("已使用系统字体")
				SPUtil.remove(SPUtil.book_typeface, SPUtil.SP_SYSTEM_SETUP)
				//刷新布局
				listViewAdapter.notifyDataSetChanged()
			}
		}else if(typeface.progress != null){//存在进度，说明正在下载中
			setViewText(view, R.id.tv_typeface_size, "${sizeStr}(${typeface.progress}%)")
			tvTypefaceDownload.text = "下载中"
			tvTypefaceDownload.setOnClickListener {
				ToastUtils.toast("文件正在下载中，请稍候")
			}
		}else if(curSelectTypeface == typeface.fileName && isFileExist){//当前选择的文件
			tvTypefaceDownload.text = "已使用"
			tvTypefaceDownload.background = this.getDrawable(R.drawable.selector_round_btn_disabled)
			tvTypefaceDownload.setOnClickListener {}
		}else if(isFileExist){//判断本地文件是否存在
			tvTypefaceDownload.text = "使用"
			tvTypefaceDownload.background = this.getDrawable(R.drawable.selector_round_btn_primary)
			tvTypefaceDownload.setOnClickListener {
				this.useTypeface(typeface)
				//刷新布局
				listViewAdapter.notifyDataSetChanged()
			}
			if(isManagerMode){
				ivTypefaceDelete.visibility = View.VISIBLE
			}
		}else{//文件不存在，显示下载按钮
			tvTypefaceDownload.text = "下载"
			tvTypefaceDownload.background = this.getDrawable(R.drawable.selector_round_btn_orange)
			tvTypefaceDownload.setOnClickListener{
				val intent = Intent()
				val path = Constant.TypefacePath
				intent.putExtra("path", path)
				intent.putExtra("name", typeface.fileName)
				intent.putExtra("size", size)
				intent.putExtra("url", typeface.url)
				intent.putExtra("key", typeface.typeCode)
				downloadUtil.startDownload(intent)
				tvTypefaceDownload.isClickable = false
			}
		}
	}

	/**使用字体文件*/
	private fun useTypeface(typeface: AppTypeface){
		ToastUtils.toast("使用字体文件：${typeface.typeName}")
		SPUtil.put(SPUtil.book_typeface, typeface.fileName!!, SPUtil.SP_SYSTEM_SETUP)
	}

	/**删除字体文件*/
	private fun deleteTypefaceFile(typeface: AppTypeface){
		if(!TextUtils.isEmpty(typeface.fileName)){
			val file = File(Constant.TypefacePath, typeface.fileName)
			if(file.exists()){
				file.delete()
				updateListItem(typeface)
				ToastUtils.toast("字体文件删除成功")
			}
		}
	}

	override fun onDestroy() {
		//此处不应该销毁，不然页面一退出文件都不见了，会出现一堆奇奇怪怪的问题
//		downloadUtil.onDestroy()
		super.onDestroy()
	}

	private fun setViewText(view: View, id: Int, text: String?){
		view.findViewById<TextView>(id).text = text
	}

	override fun onError(code: Int, err: ApiErrorResult) {
	}

	override fun onSuccess(result: ApiResult, code: Int) {
		when(code){
			//获取字体列表
			Constant.HTTP_KEY_APP_GET_TYPEFACE_LIST->{
				val list = result.getList(AppTypeface::class.java)
				appTypefaceRepository.saveAll(list)
				//刷新数据
				this.initListData(list)
				listViewAdapter.notifyDataSetChanged()
			}
		}
	}

}